/**
 * Create by richliu1023
 * @date 16/5/19
 * @email richliu1023@gmail.com
 * @github https://github.com/RichLiu1023
 * @description a simple explanation
 */
class MainLoader {

	private _main:Main;

	private isThemeLoadEnd:boolean = false;
	private isResourceLoadEnd:boolean = false;

	private _loadGroupName:string = 'login';

	public constructor( $main:Main ) {
		this._main = $main;
		var assetAdapter = new AssetAdapter();
		this._main.stage.registerImplementation( "eui.IAssetAdapter", assetAdapter );
		this._main.stage.registerImplementation( "eui.IThemeAdapter", new ThemeAdapter() );
		RES.addEventListener( RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this );
		RES.loadConfig( "resource/default.res.json", "resource/" );
	}

	private onConfigComplete( event:RES.ResourceEvent ):void {
		RES.removeEventListener( RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this );
		var theme = new eui.Theme( "resource/default.thm.json", this._main.stage );
		theme.addEventListener( eui.UIEvent.COMPLETE, this.onThemeLoadComplete, this );

		rm.AppLoaderControl.instance.addEventListener( rm.AppLoaderEvent.LOAD_COMPLETE,
													   this.onFirstLoadingComplete,
													   this );
		rm.AppLoaderControl.instance.loadGroup( 'loading', false );
	}

	private onFirstLoadingComplete():void {
		rm.AppLoaderControl.instance.removeEventListener( rm.AppLoaderEvent.LOAD_COMPLETE,
														  this.onFirstLoadingComplete,
														  this );
		this._main.startSetup();
		rm.AppLoaderControl.instance.addEventListener( rm.AppLoaderEvent.LOAD_COMPLETE,
													   this.onResourceLoadComplete,
													   this );
		rm.AppLoaderControl.instance.loadGroup( this._loadGroupName );
	}

	private onThemeLoadComplete():void {
		this.isThemeLoadEnd = true;
		this.createScene();
	}

	private onResourceLoadComplete( event:egret.Event ):void {
		if ( event.data.groupName == this._loadGroupName ) {
			rm.AppLoaderControl.instance.removeEventListener( rm.AppLoaderEvent.LOAD_COMPLETE,
															  this.onResourceLoadComplete,
															  this );
			this.isResourceLoadEnd = true;
			this.createScene();
		}
	}

	private createScene() {
		this.isThemeLoadEnd && this.isResourceLoadEnd && this._main.startCreateScene();
	}
}